(* Mathematica Package *)

(* Created by the Wolfram Workbench Jan 31, 2014 *)

BeginPackage["ThinFilmNLSupdater`"]
(* Exported symbols added here with SymbolName::usage *) 

CheckUpdate::usage = "Check if there is a new release"


Begin["`Private`"]
(* Implementation of the package *)

release[filetext_String] := 
  StringTrim[filetext, RegularExpression["\n.*"]];

DownloadsServer = "http://massaricloud.chem.umn.edu/"


CheckUpdate[PackageDirectory_String]:= 
	Module[{package = FileBaseName[Last@FileNameSplit[PackageDirectory]], ServerDirectory, PackageZip},

	ServerDirectory = DownloadsServer <> package <> "/";
	release["newest"] = Import[ServerDirectory <> "releasenotes.txt"];
	(*Print[release["newest"]];
	Print[PackageDirectory];*)
 	release["file"] = FileNameJoin[{PackageDirectory, "releasenotes.txt"}];

 		If[!FileExistsQ[release["file"]], 
 			Export[release["file"], release["newest"]],
  			release["current"] = Import@release["file"];
  			If[Greater @@ (Total[ToCharacterCode[release[#]]]& /@ {release["newest"], release["current"]}), 
  				If[
  					ChoiceDialog[Column@{"Update Available for " <> package <> " package\n", 
  										 "Current:\n" <> release@release["current"], 
       									 "Available:\n" <> release["newest"],
       									 "\n\nWARNING: \nUpdating will Quit[] the current Mathematica Kernel", 
										  "Any unsaved symbol definitions will be lost"}, 
								 {"Update" -> True, "Cancel" -> False}], 
								 	{<< "Utilities`URLTools`";
								 	 PackageZip = URLSave[DownloadsServer <> package <> "/" <> package <> ".zip", 
       													  FileNameJoin[{$TemporaryDirectory, package <> ".zip"}]];
       													  (*Print@PackageZip;*)
       								PacletManager`ZipExtractArchive[PackageZip, ParentDirectory[PackageDirectory], 
      												   "Overwrite" -> True, "Verbose" -> True];
      												  
     								 Export[FileNameJoin[{PackageDirectory, "previouslyinstalledrelease.txt"}], release["current"]]; 
     								 DeleteFile[PackageZip];
     								 
     								 Exit[]}]]]]




End[]

EndPackage[]

